/*
 * @Author: shiyue 2647472992@qq.com
 * @Date: 2024-02-16 21:15:01
 * @LastEditors: shiyue 2647472992@qq.com
 * @LastEditTime: 2024-02-17 10:27:49
 * @FilePath: /vscodecpp/test-2-16/TcpServe.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once
#include "Socket.hpp"
#include "ServeCal.hpp"
#include <iostream>
#include <functional>
#include <unistd.h>
using func = std::function<std::string(std::string &package)>;
class Tcp
{
public:
    Tcp(uint16_t port, func callback)
        : port_(port), callback_(callback)
    {
    }
    ~Tcp() {}
    void Init()
    {
        listen_socket.Build_Socket();
        listen_socket.Bind(port_);
        listen_socket.Listen();
    }
    void Start()
    {
        while (true)
        {
            std::string clientip;
            uint16_t clientport;
            int sockfd = listen_socket.Accept(&clientip, &clientport);
            if (sockfd < 0)
                continue;
            std::cout << "收到link"
                      << "clientip = " << clientip << "clientport = " << clientport << std::endl;

            if (fork() == 0)
            { 
                listen_socket.Close();
                std::string inbuff_stream;
                while (true)
                {
                    char buff[1024];
                    int n = read(sockfd, buff, sizeof(buff));
                    if (n <= 0)
                        break;
                    buff[n] = 0;
                    inbuff_stream += buff;
                    std::cout << "正在读入" << inbuff_stream << std::endl;
                    std::string info = callback_(inbuff_stream);
                    std::cout << "写入的内容" << info << std::endl;
                    write(sockfd, info.c_str(), info.size());
                }
            }
            
        }
        exit(0);
    }

private:
    uint16_t port_;
    Socket listen_socket;
    func callback_;
};